import React, {useEffect, useState} from "react";
import {Button, Col, Form, Input, message, Modal, Radio, Row, Select, TreeSelect} from 'antd';
import {deptTreeSelect} from "@/clientApi/system/dept";
import {setKeyUtils} from "@/utils/Z";
import {addUser, getUser, updateUser} from "@/clientApi/system/user";
import styles from "./index.module.css";
import { globalMessage } from "@/utils/message";


// 定义组件的 props 类型
interface MyComponentProps {
    open: boolean;
    title?: string;
    OnCanCle: () => void;
    userId?: string|undefined;

}

const EditUserView: React.FC<MyComponentProps> = (props) => {
    const [form] = Form.useForm();
    const [deptOptions, setDeptOptions] = useState<any[]>([]);
    // 表单的值
    const [formData, setFormData] = useState({})
    // 岗位下来数据
    const [postOptions, setPostOptions] = useState([])
    // 角色下拉数据
    const [roleOptions, setRoleOptions] = useState([])


    function handleCancel() {
        props.OnCanCle()
    }

    useEffect(() => {
        // console.log(props.userId, 'props?.userId')
        getTreeSelect()
        if (props.userId) {
            getUserData(props.userId)
        } else {
            form.setFieldsValue({
                deptId:'',
                nickName: '',
                phonenumber:  "",
                email:  "",
                userName:  "",
                password:  '',
                sex:  "0",
                status: '0',
                postIds:  [],
                roleIds:  [],
                remark:  '',
            });
        }


    }, [props.userId]);
    const getUserData = (id?: string) => {

        getUser(id).then((res:any) => {
            if (res?.code === 200) {
                setFormData(res.data)
                setPostOptions(setKeyUtils(res.posts, {value: 'postId', label: 'postName'}))
                setRoleOptions(setKeyUtils(res.roles, {value: 'roleId', label: 'roleName'}))
                form.setFieldsValue({
                    deptId: res.data?.deptId || '',
                    nickName: res.data?.nickName || '',
                    phonenumber: res.data?.phonenumber || "",
                    email: res.data?.email || "",
                    userName: res.data?.userName || "",
                    password: res.data?.password || '',
                    sex: res.data?.sex || "0",
                    status: res.data?.status || '0',
                    postIds: res?.postIds || [],
                    roleIds: res?.roleIds || [],
                    remark: res.data?.remark || '',
                });
            }
        });

    };
    /** 查询部门下拉树结构 */
    const getTreeSelect = () => {
        deptTreeSelect().then((res: any) => {
            setDeptOptions(res.data)
        });
    };
    const onValuesChange = (changedValues: any, allValues: any) => {
        if (props.userId !== undefined) {
            setFormData((prevState: any) => ({
                ...prevState, ...changedValues
            }));
        } else {
            setFormData((prevState: any) => ({
                ...allValues
            }));
        }

    };
    const handleSubmit = () => {
        if (props.userId !== undefined) {
            updateUser(formData).then((res:any) => {
                 globalMessage().warning(res.msg).then(r => {})
                props.OnCanCle()
            });
        } else {
            addUser(formData).then((res:any) => {
                 globalMessage().warning(res.msg).then(r => {})
                props.OnCanCle()
            });
        }
    }
    return (
        <>
            <Modal
                forceRender
                open={props.open}
                title={props.title}
                footer={null}
                onCancel={() => {
                    props.OnCanCle()
                }}
            >
                <Form form={form}
                      name="edituser"
                      style={{maxWidth: 800}}
                      onValuesChange={onValuesChange}>
                    <Row gutter={10}>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="用户昵称"
                                name="nickName"
                                rules={[{required: true, message: "用户昵称不能为空", validateTrigger: "blur"}]}
                            >
                                <Input/>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="归属部门"
                                name="deptId"
                                rules={[
                                    {
                                        required: true,
                                    },
                                ]}
                            >
                                <TreeSelect
                                    showSearch
                                    style={{width: '100%'}}
                                    // defaultValue={formData.userId}
                                    dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                                    placeholder="请选择"
                                    treeDefaultExpandAll
                                    treeData={setKeyUtils(deptOptions, {value: 'id', title: 'label'})}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="手机号码"
                                name="phonenumber"
                                rules={
                                    [{
                                        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                                        message: "请输入正确的手机号码",
                                        validateTrigger: "blur"
                                    }]
                                }
                            >
                                <Input/>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="邮箱"
                                name="email"
                                rules={[{
                                    type: "email",
                                    message: "请输入正确的邮箱地址",
                                    validateTrigger: ["blur", "change"]
                                }]}
                            >
                                <Input/>
                            </Form.Item>
                        </Col>
                        {props.userId === undefined && (<Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="用户名称"
                                name="userName"
                                rules={[{required: true, message: "用户名称不能为空", validateTrigger: "blur"}, {
                                    min: 2,
                                    max: 20,
                                    message: "用户名称长度必须介于 2 和 20 之间",
                                    validateTrigger: "blur"
                                }]}
                            >
                                <Input/>
                            </Form.Item>
                        </Col>)}
                        {props.userId === undefined && (<Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="用户密码"
                                name="password"
                                rules={[{required: true, message: "用户密码不能为空", validateTrigger: "blur"}, {
                                    min: 5,
                                    max: 20,
                                    message: "用户密码长度必须介于 5 和 20 之间",
                                    validateTrigger: "blur"
                                }, {
                                    pattern: /^[^<>"'|\\]+$/,
                                    message: "不能包含非法字符：< > \" ' \\\ |",
                                    validateTrigger: "blur"
                                }]}
                            >
                                <Input/>
                            </Form.Item>
                        </Col>)}
                        <Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="用户性别"
                                name="sex"
                            >
                                <Select
                                    style={{width: "100%"}}
                                    options={[{value: '0', label: '男'}, {value: '1', label: '女'}, {
                                        value: '2',
                                        label: '未知'
                                    },]}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="状态"
                                name="status">
                                <Radio.Group
                                >
                                    <Radio value={"0"}>正常</Radio>
                                    <Radio value={"1"}>停用</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="岗位"
                                name="postIds"
                            >
                                <Select
                                    mode="multiple"
                                    style={{width: "100%"}}
                                    options={postOptions}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{span: 8,}}
                                label="角色"
                                name="roleIds"
                            >
                                <Select
                                    mode="multiple"
                                    style={{width: "100%"}}
                                    options={roleOptions}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                labelCol={{span: 4,}}
                                label="备注"
                                name="remark"
                            >
                                <Input.TextArea/>
                            </Form.Item>
                        </Col>

                        <Col span={24}>
                            <Form.Item
                                wrapperCol={{offset: 16, span: 8}}
                            >
                                <div className={styles.buttonClass}>
                                    <Button type="primary" htmlType="submit" onClick={handleSubmit}>确认</Button>
                                    <Button type="primary" onClick={handleCancel}>取消</Button>
                                </div>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>

        </>
    )
};
export default EditUserView;
